package it.polito.connectedcar.message;

import it.polito.connectedcar.tcc.zone.Token;
import it.polito.connectedcar.tcc.zone.ZoneToken;
import it.polito.connectedcar.util.Constants;
import it.polito.connectedcar.vehicle.SUMOVehicleToken;

/**
 * This message is used for vehicle to vehicle communication. Vehicles exchange
 * their position,speed and direction in order to preemptively alert about
 * possible collisions. In order for a message coming from a vehicle , to be
 * accepted by the receiving vehicle, 2 conditions must apply :
 * <ol>
 * <li>the source address of the sender must be known by the receiver in some of
 * the current managed tokens</li>
 * <li>the token used by the sender to identity its belonging group must be the
 * same as the one known by the receiver</li>
 * </ol>
 * If one of these conditions does not apply , the message has to dropped
 * 
 * @author Nicola Aresta
 * 
 */
public class VehicleFromVehicleMessage extends IncomingMessage {

	private Double speed;
	private Double direction;
	private Double utmXPos;
	private Double utmYPos;
	private String currentLaneId;
	private Token belongingToken;
	private Token vehicleIdentifier;

	public VehicleFromVehicleMessage(byte[] data) {
		super(data, Constants.VEHICLE_TYPE_CODE);
	}

	/**
	 * Extraction of all the vehicles parameters : position , speed , direction
	 */
	@Override
	protected boolean onProcessMessage(Storage st) {
		try {

			/**
			 * 1-sourcetype : 4 bit 2-actiontype : 4 bit 3-token : TOKEN_LENGTH
			 * bytes 4- xpos -> double 5- yPos -> double 6- direction -> double
			 * 7- speed -> double
			 */
			if (sourceTypeCode != Constants.VEHICLE_TYPE_CODE || actionCode != Constants.VEHICLE_UPDATE_MESSAGE_CODE)
				return false;

			byte[] token = new byte[TOKEN_LENGTH];
			for (int i = 0; i < TOKEN_LENGTH; i++)
				token[i] = (byte) st.readByte();
			belongingToken = new ZoneToken(token);
			// FIXME : remove the vehicle identifier
			vehicleIdentifier = new SUMOVehicleToken(st.readStringASCII());

			utmXPos = st.readDouble();
			utmYPos = st.readDouble();
			direction = st.readDouble();
			speed = st.readDouble();
			currentLaneId = st.readStringASCII();

		} catch (IllegalStateException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	protected void convertFromData(Storage st) {
		// TODO Auto-generated method stub

	}

	public Double getSpeed() {
		return speed;
	}

	public Double getDirection() {
		return direction;
	}

	public Double getUtmXPos() {
		return utmXPos;
	}

	public Double getUtmYPos() {
		return utmYPos;
	}

	public Token getBelongingToken() {
		return belongingToken;
	}

	public String getCurrentLaneId() {
		return currentLaneId;
	}

	public void setCurrentLaneId(String currentLaneId) {
		this.currentLaneId = currentLaneId;
	}

	public Token getVehicleIdentifier() {
		return vehicleIdentifier;
	}

}
